-- Mysql服务
-- Author: Colocasia
-- Date: 2018-03-14

local skynet = require "skynet";
require "skynet.manager";
local mysql = require "skynet.db.mysql";
local log = require "log";


local us_mysql = {};
local pool = {};

local maxconnect = nil;
local index = 2;

local function getconn(sync)
    local db = nil;

    if true == sync then
        db = pool[1];
    else
        db = pool[index];
        index = index + 1;
        if index > maxconnect then
            index = 2;
        end
    end

    return db;
end

-- test conn
function us_mysql.test(dbc)
    -- local res = pool[1]:query("select * from account");
    -- log.dump(res);
    log.printf("us_mysql.test")
    log.dump(dbc);
end

-- execute sql
-- pool 1   is write
-- pool 2-n is read
function us_mysql.execute(sql, sync)
    local db = getconn(sync);
    assert(db);
    return db:query(sql);
end

-- start service
function us_mysql.start()
    maxconnect = 10;
    assert(maxconnect >= 2);

    for i=1, maxconnect do
        local function on_connect(db)
            table.insert(pool, db);
            db:query("set charset utf8");
            -- log.printf("mysql connect success! index=>%s", #pool);
        end
        local db = mysql.connect({
            host = "127.0.0.1",
            port = 3306,
            database = "test",
            user = "root",
            password = "111111",
            max_packet_size = 1024 * 1024,
            on_connect = on_connect
        })
        if not db then
            log.printf("mysql connect error");
        end
    end
    return true;
end

function us_mysql.init()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        local f = assert(us_mysql[cmd], "us_mysql cmd=>"..cmd.." not found");
        skynet.retpack(f(...));
    end)
    skynet.register(SERVICE_NAME);
end

skynet.start(us_mysql.init);

